import {Injectable} from '@angular/core';
import {InterfaceProvider} from "@providers/interface";
import {Events} from "ionic-angular";
import {StorageProvider} from "@providers/storage";

/*
  Generated class for the ChatProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class ChatProvider {

  roomListener: any[] = [];

  constructor(private ifp: InterfaceProvider,
              private events: Events,
              private storage: StorageProvider,
  ) {
  }

  onMessage(msg) {
    let room_id = msg['room_id'];
    this.roomListener.forEach((value: ChatListener) => {
      if (value.room_id == room_id) {
        value.onMessage(msg);
      }
    });
  }

  sendMessage(room_id: string, type: string, content: any) {
    let userInfo = this.storage.getUserInfo();

    this.events.publish("websocket:sendMessage", {
      person_id: userInfo['SessionID'],
      person_name: userInfo['USERNAME'],
      room_id: room_id,
      content: content,
      type: type,
      topic: 'chat:message',
    });

  }

  registerListener(page: ChatListener) {
    let index = this.roomListener.indexOf(page);
    if (index == -1) this.roomListener.push(page);
  }

  unregisterListener(page: ChatListener) {
    let index = this.roomListener.indexOf(page);
    if (index != -1) this.roomListener.splice(index, 1);
  }

  chatHistory(room_id, page_num, page_size): Promise<any> {
    return this.ifp.post({
      interfaceId: "app.chat.chatHistory",
      data: {room_id: room_id, page_num: page_num, page_size: page_size}
    }).toPromise();
  }

  getRoomList(): Promise<any> {
    let userInfo=this.storage.read("userInfo");
    return this.ifp.post({
      interfaceId: "app.chat.getRoomList",
      data: userInfo || {}
    }).toPromise();
  }
}

export interface ChatListener {
  room_id: string
  person_id: string
  onMessage: Function;
}
